package com.ckjava.test.web.base;

import com.ckjava.test.domain.base.BaseJpaEntity;
import com.ckjava.test.service.base.BaseJpaCrudService;
import com.ckjava.xutils.Constants;
import com.ckjava.xutils.http.HttpResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api
public abstract class BaseJpaCrudController<S extends BaseJpaCrudService, E extends BaseJpaEntity> extends CorsController implements Constants {

    @Autowired
    public S service;

    @ApiOperation("根据 id 获取一个对象")
    @GetMapping("/{id}")
    public HttpResponse<Object> get(
            @PathVariable Long id) {
        return HttpResponse.getReturn(service.get(id), HttpResponse.SUCCESS, null);
    }

    @ApiOperation("获取所有的对象")
    @GetMapping(value = "/all")
    public HttpResponse<List<E>> findAll() {
        return HttpResponse.getReturn(service.findAll(), HttpResponse.SUCCESS, null);
    }

    @ApiOperation("保存或者修改一个对象")
    @PostMapping
    public HttpResponse<String> saveOrUpdate(
            @RequestBody E e) {
        service.saveOrUpdate(e);
        return HttpResponse.getReturn(HttpResponse.SUCCESS, HttpResponse.SUCCESS, null);
    }

    @ApiOperation("根据 id 删除一个对象")
    @DeleteMapping("/{id}")
    public HttpResponse delete(
            @PathVariable Long id) {
        service.delete(id);
        return HttpResponse.getReturn(null, HttpResponse.SUCCESS, null);
    }
}
